import React, { Component } from 'react'
import { observer,inject } from 'mobx-react'
import * as mobx from 'mobx'
import StoreItemListForm from './StoreItemList'
import ShopItemLogTable from '../LogQuery/ShopItemLog/shopItemLogTable'
import InventoryLogTable from '../LogQuery/InventoryLog/inventoryLogTable'
import { Button, Table, Modal, message, Radio , Row , Col, Menu, Tooltip,Spin, InputNumber, Tag} from 'antd'
import StoreItemDetail from './StoreItemDetail'
import './index.css'
const confirm = Modal.confirm
const RadioGroup = Radio.Group
const SubMenu = Menu.SubMenu

@inject('storeItemStore')@inject('store')@observer
class StoreItemComponent extends Component {
  
  constructor(props) {
    super(props)
    this.collapse = false
  }
  

  state = {
    dataSource : [],
    pagination: {},
    selectedKeys: '',
    selectedRows:[],
    formList:{},
    statusModal: false,
    detailModal: false,
    shelvedModal: false,
    lockPriceModal: false,
    lockInventoryModal: false,
    formSource : {},
    formLoading: true,
    o2oSkuId: '',
    itemId: 0,
    channelId: 0,
    shopId: '',
    skuId: '',
    statusValue: 1,
    shelvedValue: 1,
    lockPriceValue: null,
    lockInventoryValue: null,
    unableStatus: true,
    changeShopId: null,
    changeChannelId: null,
    status: null,
    unableState: false,
    logVisible: false,
    logChannelId: undefined,
    logShopId : undefined,
    logItemId: undefined,
    inventoryChannelId: undefined,
    inventoryShopId : undefined,
    inventoryitemCode :undefined,
    inventoryVisible : false,
    categoryId: '',
    treeSelectedKeys:[],
    categoryList: [],
    confirmLoading: false,
    lockRefresh: false,
    refreshValue: 0,
    personnalStatus: false,
    checkStatus: false,
    widowHeight: document.body.offsetHeight,
    categoryParams: {}
  }

  componentDidMount= async () => {
    const shopId = window.location.hash.split('#')[1].split('/')[3]
    const channelId = window.location.hash.split('#')[1].split('/')[4]
    const page = this.state.pagination.current
    const pageSize = this.state.pagination.pageSize
    let categoryList = []
    window.addEventListener('resize', this.onWindowResize)
    this.setState({
      changeShopId: shopId,
      changeChannelId: channelId
    })
    const shopIdList = [shopId]
    if(shopId && channelId) {
      this.changeMsgData(page, pageSize, shopIdList, channelId)
      const params = Object.assign({shopId:shopIdList, channelId: channelId}, ...this.state.categoryParams)
      categoryList = await this.initCategoryList(params)
    }else{
      // this.changeMsgData()
      categoryList = await this.initCategoryList({})
    }
    this.setState({
      categoryList : categoryList
    })
  }

  changeCategoryList  = data =>{
    this.setState({
      categoryList: data
    })
  }
  componentWillUnmount(){ 
    this.setState = (state,callback)=>{
      return;
    };  
    window.removeEventListener('resize', this.onWindowResize)
}

  componentWillReceiveProps(nextProps) {
  }

  onWindowResize = () => {
    this.setState({
      widowHeight: document.body.offsetHeight
    })
  }

  changeMsgData = async (page, pageSize, shopId, channelId, o2oItemId, goodsName, barcode, itemCode, shelved, status, categoryId, isSelf, city) =>{
    const msgListData = await this.props.storeItemStore.getGoodsListData(page, pageSize, shopId, channelId, o2oItemId, goodsName, barcode, itemCode, shelved, status, categoryId, isSelf, city)
    this.init(msgListData)
    this.props.storeItemStore.closeLoading()
  }

  handleChange = (pagination) => {
    this.refs.storeItemListForm.validateFieldsAndScroll((err , values) => {
      const shopId  = typeof(values.shopId) === 'string' ? [this.props.storeItemStore.shopId] : values.shopId    
      let channelId = (values.channelId === '百度外卖' ? 10 : values.channelId) || (values.channelId === '饿了么' ? 11 : values.channelId) || (values.channelId === '美团' ? 12 : values.channelId)
      const o2oItemId = values.o2oItemId
      const goodsName = values.goodsName
      const barcode = values.barcode
      const itemCode = values.itemCode
      const shelved = values.shelved
      const status = values.status
      const isSelf = values.isSelf
      const city = values.city === '全部' ? '' : values.city
    this.changeMsgData(pagination.current, pagination.pageSize, shopId, channelId, o2oItemId, goodsName, barcode, itemCode, shelved, status, this.state.categoryId, isSelf, city)    
    })
    this.setState({
      ...pagination,
      current: pagination.current,
      pageSize: pagination.pageSize
    })
    this.handleRowSelectChange([],[])
  }

  init = (msgListData) =>{
    const dataSource = this.dataSourceFun(msgListData)
    this.setState({
      dataSource
    })
  }
  
  initCategoryList = async (params) =>{
    let categoryList= []
    if(params !==undefined){
      await this.props.storeItemStore.getCategoryList(params)
      categoryList = mobx.toJS(this.props.storeItemStore.categoryList)
    }else{
      await this.props.storeItemStore.getCategoryList()
      categoryList = mobx.toJS(this.props.storeItemStore.categoryList)    
    }
    return categoryList
  }

  dataSourceFun = (msgListData) =>{
    if(msgListData.length !==0){
      const dataSource = msgListData.data.data.map( data =>{
        return {
          key : data.key,
          channelName: data.channelName,
          shopId: data.shopId,
          isSelf: data.isSelf === 0 ? '否' : '是',
          channelId: data.channelId,
          itemCode: data.itemCode,
          o2oSkuId: data.o2oSkuId,
          inventoryModifyTime: data.inventoryModifyTime,
          priceModifyTime: data.priceModifyTime,
          safeInventory: data.safeInventory,
          skuId: data.skuId,
          p4Inventory: data.p4Inventory,
          saleQty: data.saleQty,
          inventoryModifyTime: data.inventoryModifyTime,
          priceRate: data.priceRate,
          categoryName: data.categoryName,
          categoryId: data.categoryId,
          goodsName: data.goodsName,
          barCode: data.barcode,
          actualInventory: data.actualInventory,
          salesPrice: data.salesPrice,
          costPrice: data.costPrice,
          shelved: data.shelved === 0 ? '下架' : '上架',
          itemId: data.itemId,
          status: (data.status ===0 && '未启用') ||  (data.status ===1 && '启用') ||  (data.status ===-1 && '禁用'),
          shopNameAlias: data.shopNameAlias,
          lockInventory: data.lockInventory,
          lockPrice: data.lockPrice,
          sysInventory: data.sysInventory === 0 ? '未同步' : '同步',
          goodsEnName: data.goodsEnName,
          spec: data.spec,
          unit: data.unit
        }
      })
      this.paginationFun(msgListData)
      return dataSource
    }
  }

  paginationFun = (data) => {
    const total = data.data.total
    if(total === -1) {
      return false;
    }
    this.setState({
      pagination :{
        total,
        showTotal: () => `共${total}条数据`,
        pageSizeOptions: ['10', '20', '50', '100'],
        showSizeChanger: true,
      }
    })
  }

  showDetailModal = async(skuId, channelId, itemId, shopId, status) => {
    const result = await this.props.storeItemStore.getGoodsData(skuId, channelId, itemId)
    let chooseCategoryIdValue = []
    if(this.state.categoryList.length !== 0){
      this.setState({
        detailModal: true,
        skuId,
        itemId,
        shopId,
        channelId,
        status
      })
      if(status === -1){
        this.setState({
          unableState: true
        })
      }else{
        this.setState({
          unableState: false
        })
      }
      const chooseCategoryIdList =this.state.categoryList.find( v =>v.categoryId===result.data.data.categoryId)
      chooseCategoryIdValue.push(chooseCategoryIdList.parentCategoryId, chooseCategoryIdList.categoryId )
      this.setState({
        formSource: {
          categoryId: chooseCategoryIdValue,
          goodsName: result.data.data.goodsName,
          goodsEnName: result.data.data.goodsEnName,
          safeInventory: result.data.data.safeInventory,
          lockInventory: result.data.data.lockInventory,
          lockPrice: result.data.data.lockPrice,
          shelved: result.data.data.shelved,
          barcode: result.data.data.barcode,
          unit: result.data.data.unit,
          spec: result.data.data.spec,
          weight: result.data.data.weight,
          status: result.data.data.status,
          lockInventoryRefresh: result.data.data.lockInventoryRefresh,
          priceRate: result.data.data.priceRate
        },
        formLoading: false,
        checkStatus: result.data.data.isSelf  === 0 ? false : true,
        personnalStatus: result.data.data.isSelf === 0 ? false : true
      })
    }else{
      message.error('数据正在加载!请稍后!') 
    }
  }

  handleCancel = () => {
    this.setState({
      detailModal: false,
      formLoading: true,
      personnalStatus: false,
      checkStatus: false
    })
    this.refs.StoreItemDetail.resetFields()
  }

  changeFormList = formList =>{
    this.setState({
      formList
    })
  }

  handleOk =  () => {
    this.refs.StoreItemDetail.validateFieldsAndScroll( async (err, values) => {
      if(!err){
        if(values.lockInventory !== null && values.lockInventoryRefresh === undefined) {
          message.error('请输入锁定库存更新间隔')
        }else{
          const itemId = this.state.itemId
          const channelId = this.state.channelId
          const shopId = this.state.shopId
          const skuId = this.state.skuId
          const oldStatus = this.state.status
          const safeInventory = values.safeInventory
          const lockInventory = values.lockInventory
          const lockPrice = values.lockPrice
          const barcode = values.barcode
          const categoryId = values.categoryId[1]
          const goodsEnName = values.goodsEnName
          const goodsName = values.goodsName
          const spec = values.spec
          const unit = values.unit
          const weight = values.weight
          const priceRate = values.priceRate
          const isSelf = this.state.personnalStatus === false ? 0 : 1
          const shelved = (values.shelved === '下架' && '0') || (values.shelved === '上架' && '1')
          const newStatus = (values.status === '禁用' && '-1') || (values.status === '未启用' && '0') || (values.status === '启用' && '1')
          const lockInventoryRefresh = (values.lockInventoryRefresh === '手工触发' && '0') || (values.lockInventoryRefresh === '每天' && '1') || (values.lockInventoryRefresh === '每周' && '2') || (values.lockInventoryRefresh === '每月' && '3')
          const result = await this.props.storeItemStore.changeGoodsData(oldStatus, newStatus, itemId, channelId, shopId, skuId, safeInventory, lockInventory, lockInventoryRefresh, lockPrice, shelved, barcode, categoryId, goodsEnName, goodsName, spec, unit, weight, isSelf, priceRate)
          if(result.data.status === 200){
            message.success('修改成功')
            this.setState({
              detailModal: false,
              formLoading: true,
              personnalStatus: false,
              checkStatus: false
            })
            this.refs.StoreItemDetail.resetFields()
            if(this.state.changeChannelId !==undefined && this.state.changeShopId !== undefined){
              const {o2oSkuId, goodsName, barcode, itemCode, shelved, status, isSelf, city} = this.state.formList
              const shopId = this.state.changeShopId 
              const channelId = this.state.changeChannelId
              const page = this.state.pagination.current
              const pageSize = this.state.pagination.pageSize
              this.changeMsgData(page, pageSize, [shopId], channelId, o2oSkuId, goodsName, barcode, itemCode, shelved, status, this.state.categoryId, isSelf, city)
            }else{
              const {shopId, channelId, o2oSkuId, goodsName, barcode, itemCode, shelved, status, isSelf, city} = this.state.formList             
              const page = this.state.pagination.current
              const pageSize = this.state.pagination.pageSize  
              if(shopId === undefined){
              this.changeMsgData(page, pageSize, [], channelId, o2oSkuId, goodsName, barcode, itemCode, shelved, status, this.state.categoryId, isSelf, city)                
              }else{
                this.changeMsgData(page, pageSize, [shopId], channelId, o2oSkuId, goodsName, barcode, itemCode, shelved, status, this.state.categoryId, isSelf, city)
              }      
            }
          }else{
            message.error(result.data.err)
          }
        }
      }
      
    })
  }

  changePersonnal = (data) =>{
    this.setState({
      personnalStatus: data
    })  
  }

  changeChecked = (data) =>{
    this.setState({
      checkStatus: data
    }) 
  }
  onChangeStatus = (e) =>{
    e.preventDefault();
    this.setState({
      statusValue: e.target.value
    })
    
  }

  onChangeShelved = (e) =>{
    e.preventDefault();
    this.setState({
      shelvedValue: e.target.value
    })    
  }

  onChangeRefresh = (e) =>{
    e.preventDefault()
    this.setState({
      refreshValue: e.target.value
    })
  }

  onChangelockPrice = (value) =>{
    this.setState({
      lockPriceValue:value
    })  
  }

  onChangelockInventory = (value) =>{
    this.setState({
      lockInventoryValue: value
    })    
  }

  setStatus = () =>{
    if (this.state.selectedRows.length !== 0) {
      this.setState({statusModal: true})
    } else {
      Modal.warning({
        title: '启用商品',
        content: '请至少选择一件商品！',
      })
    }
  }
  
  setShelved = () =>{
    if (this.state.selectedRows.length !== 0) {
      this.setState({shelvedModal: true})
    } else {
      Modal.warning({
        title: '上架商品',
        content: '请至少选择一件商品！',
      })
    }
  }

  setLockPrice = () =>{
    if (this.state.selectedRows.length !== 0) {
      this.setState({lockPriceModal: true})
    } else {
      Modal.warning({
        title: '商品价格锁定',
        content: '请至少选择一件商品！',
      })
    }
  }

  setLockInventory = () =>{
    if (this.state.selectedRows.length !== 0) {
      this.setState({lockInventoryModal: true})
    } else {
      Modal.warning({
        title: '商品库存锁定',
        content: '请至少选择一件商品！',
      })
    }
  }

  setRefresh = () =>{
    let that = this
    confirm({
      title: '手工触发更新',
      content: '是否更新所有手工触发的锁定库存',
      okText: '是',
      cancelText: '否',
      onOk() {
        that.handleRefresh()
      },
    });
  }

  handleStatus = async () =>{
    this.setState({
      confirmLoading: true
    })   
    const newStatus = this.state.statusValue
    const selectRow = []
    this.state.selectedRows.forEach(data => {
      const oldStatus = (data.status === '禁用' && -1) || (data.status === '未启用' && 0) || (data.status === '启用' && 1)
      selectRow.push({
        skuId: data.skuId,
        channelId: data.channelId,
        shopId: data.shopId,
        oldStatus : oldStatus,
        newStatus: newStatus
      })
    })
    const result = await this.props.storeItemStore.updateO2oGoodsStatus(selectRow)
    if(result.data.status ===200){
      message.success('操作成功')
      this.setState({
        statusModal: false,
        confirmLoading: false,
        selectedKeys: []
      })
      if(newStatus === 1){
        this.setState({
          unableStatus:true
        })
      }
      if(this.state.changeChannelId !==null && this.state.changeShopId !== null){
        this.refs.storeItemListForm.validateFieldsAndScroll((err , values) => {
          const o2oItemId = values.o2oItemId
          const goodsName = values.goodsName
          const barcode = values.barcode
          const itemCode = values.itemCode
          const shelved = values.shelved
          const status = values.status    
          const shopId = this.state.changeShopId 
          const channelId = this.state.changeChannelId
          const page = this.state.current
          const pageSize = this.state.pageSize 
          const isSelf = values.isSelf
          const city = values.city === '全部' ? '' : values.city
        this.changeMsgData(page, pageSize, [shopId], channelId,o2oItemId, goodsName, barcode, itemCode, shelved, status, this.state.categoryId, isSelf, city)          
        })
      }else{
        this.refs.storeItemListForm.validateFieldsAndScroll((err , values) => {
          const shopId  = typeof(values.shopId) === 'string' ? [this.props.storeItemStore.shopId] : values.shopId  
          let channelId = (values.channelId === '百度外卖' ? 10 : values.channelId) || (values.channelId === '饿了么' ? 11 : values.channelId) || (values.channelId === '美团' ? 12 : values.channelId)
          const o2oItemId = values.o2oItemId
          const goodsName = values.goodsName
          const barcode = values.barcode
          const itemCode = values.itemCode
          const shelved = values.shelved
          const status = values.status 
          const page = this.state.current
          const pageSize = this.state.pageSize 
          const isSelf = values.isSelf
          const city = values.city === '全部' ? '' : values.city
        this.changeMsgData(page, pageSize, shopId, channelId,o2oItemId, goodsName, barcode, itemCode, shelved, status, this.state.categoryId, isSelf, city)          
        })
      }
    }else{
      message.error(result.data.err)
      this.setState({
        confirmLoading: false        
        })
    }
  }

  handleRefresh = async () =>{
      this.setState({
        confirmLoading: true
      }) 
       const result = await this.props.storeItemStore.insertGoodsLockInventory()
       if(result.data.status === 200){
         message.success('操作成功')
         this.setState({
          confirmLoading: false ,
          lockRefresh: false
         })
       }else{
         message.error(result.data.err)
         this.setState({
          confirmLoading: false        
          })
       }
  }

  handleShelved = async () =>{
    this.setState({
      confirmLoading: true
    })   
    const shelved = this.state.shelvedValue
    const selectRow = []
    this.state.selectedRows.forEach(data => {
      const status = (data.status === '禁用' && -1)  || (data.status === '启用' && 1) || (data.status === '未启用' && 0)
      selectRow.push({
        skuId: data.skuId,
        channelId: data.channelId,
        shopId: data.shopId,
        shelved: shelved,
        oldStatus:status,
        newStatus:status
      })
    })
    const result = await this.props.storeItemStore.updateO2oGoodsShelved(selectRow)
    if(result.data.status ===200){
      message.success('操作成功')
      this.setState({
        shelvedModal: false,
        confirmLoading: false,
        selectedKeys: []
      }) 
    }else{
      message.error(result.data.err)
      this.setState({
        confirmLoading: false        
        })
    }
    if(this.state.changeChannelId !==null && this.state.changeShopId !== null){
      this.refs.storeItemListForm.validateFieldsAndScroll((err , values) => {
        const o2oItemId = values.o2oItemId
        const goodsName = values.goodsName
        const barcode = values.barcode
        const itemCode = values.itemCode
        const shelved = values.shelved
        const status = values.status 
        const shopId = this.state.changeShopId 
        const channelId = this.state.changeChannelId
        const page = this.state.current
        const pageSize = this.state.pageSize
        const isSelf = values.isSelf 
        const city = values.city === '全部' ? '' : values.city        
      this.changeMsgData(page, pageSize, [shopId], channelId,o2oItemId, goodsName, barcode, itemCode, shelved, status, this.state.categoryId, isSelf, city)          
      })
    }else{
      this.refs.storeItemListForm.validateFieldsAndScroll((err , values) => {
        const shopId  = typeof(values.shopId) === 'string' ? [this.props.storeItemStore.shopId] : values.shopId  
        let channelId = (values.channelId === '百度外卖' ? 10 : values.channelId) || (values.channelId === '饿了么' ? 11 : values.channelId) || (values.channelId === '美团' ? 12 : values.channelId)
        const o2oItemId = values.o2oItemId
        const goodsName = values.goodsName
        const barcode = values.barcode
        const itemCode = values.itemCode
        const shelved = values.shelved
        const status = values.status 
        const page = this.state.current
        const pageSize = this.state.pageSize 
        const isSelf = values.isSelf
        const city = values.city === '全部' ? '' : values.city        
      this.changeMsgData(page, pageSize, shopId, channelId,o2oItemId, goodsName, barcode, itemCode, shelved, status, this.state.categoryId, isSelf, city)          
      })
    }
  }

  handleLockPrice = async () =>{
    this.setState({
      confirmLoading: true
    })   
    const lockPrice = this.state.lockPriceValue
    const selectRow = []
    this.state.selectedRows.forEach(data => {
      const status = (data.status === '禁用' && -1)  || (data.status === '启用' && 1) || (data.status === '未启用' && 0)
      selectRow.push({
        skuId: data.skuId,
        channelId: data.channelId,
        shopId: data.shopId,
        lockPrice: lockPrice === null ? '' : lockPrice,
        oldStatus: status,
        newStatus: status
      })
    })
    const result = await this.props.storeItemStore.updateO2oGoodsLockPrice(selectRow)
    if(result.data.status ===200){
      message.success('操作成功')
      this.setState({
        lockPriceModal: false,
        confirmLoading : false,
        selectedKeys: [],
        lockPriceValue: null
      })
      if(this.state.changeChannelId !==null && this.state.changeShopId !== null){
        this.refs.storeItemListForm.validateFieldsAndScroll((err , values) => {
          const o2oItemId = values.o2oItemId
          const goodsName = values.goodsName
          const barcode = values.barcode
          const itemCode = values.itemCode
          const shelved = values.shelved
          const status = values.status 
          const shopId = this.state.changeShopId 
          const channelId = this.state.changeChannelId
          const page = this.state.current
          const pageSize = this.state.pageSize 
          const isSelf = values.isSelf
          const city = values.city === '全部' ? '' : values.city
        this.changeMsgData(page, pageSize, [shopId], channelId,o2oItemId, goodsName, barcode, itemCode, shelved, status, this.state.categoryId, isSelf, city)          
        })
      }else{
        this.refs.storeItemListForm.validateFieldsAndScroll((err , values) => {
          const shopId  = typeof(values.shopId) === 'string' ? [this.props.storeItemStore.shopId] : values.shopId  
          let channelId = (values.channelId === '百度外卖' ? 10 : values.channelId) || (values.channelId === '饿了么' ? 11 : values.channelId) || (values.channelId === '美团' ? 12 : values.channelId)
          const o2oItemId = values.o2oItemId
          const goodsName = values.goodsName
          const barcode = values.barcode
          const itemCode = values.itemCode
          const shelved = values.shelved
          const status = values.status 
          const page = this.state.current
          const pageSize = this.state.pageSize 
          const isSelf = values.isSelf
          const city = values.city === '全部' ? '' : values.city
        this.changeMsgData(page, pageSize, shopId, channelId,o2oItemId, goodsName, barcode, itemCode, shelved, status, this.state.categoryId, isSelf, city)          
        })
      }
    }else{
      message.error(result.data.err)
      this.setState({
      confirmLoading: false        
      })
    }
  }

  handleLockInventory = async () =>{
    this.setState({
      confirmLoading: true
    })   
    const lockInventory = this.state.lockInventoryValue
    const selectRow = []
    this.state.selectedRows.forEach(data => {
      const status = (data.status === '禁用' && -1)  || (data.status === '启用' && 1) || (data.status === '未启用' && 0)            
      selectRow.push({
        skuId: data.skuId,
        channelId: data.channelId,
        shopId: data.shopId,
        lockInventory: lockInventory === null ? '' : lockInventory,
        oldStatus: status,
        newStatus: status
      })
    })
    const result = await this.props.storeItemStore.updateO2oGoodsLockInventory(selectRow)
    if(result.data.status ===200){
      message.success('操作成功')
      this.setState({
        lockInventoryModal: false,
        confirmLoading: false,
        selectedKeys: [],
        lockInventoryValue: null
      })
      if(this.state.changeChannelId !==null && this.state.changeShopId !== null){
        this.refs.storeItemListForm.validateFieldsAndScroll((err , values) => {
          const o2oItemId = values.o2oItemId
          const goodsName = values.goodsName
          const barcode = values.barcode
          const itemCode = values.itemCode
          const shelved = values.shelved
          const status = values.status 
          const shopId = this.state.changeShopId 
          const channelId = this.state.changeChannelId
          const page = this.state.current
          const pageSize = this.state.pageSize 
          const isSelf = values.isSelf
          const city = values.city === '全部' ? '' : values.city
        this.changeMsgData(page, pageSize, [shopId], channelId,o2oItemId, goodsName, barcode, itemCode, shelved, status, this.state.categoryId, isSelf, city)          
        })
      }else{
        this.refs.storeItemListForm.validateFieldsAndScroll((err , values) => {
          const shopId  = typeof(values.shopId) === 'string' ? [this.props.storeItemStore.shopId] : values.shopId  
          let channelId = (values.channelId === '百度外卖' ? 10 : values.channelId) || (values.channelId === '饿了么' ? 11 : values.channelId) || (values.channelId === '美团' ? 12 : values.channelId)
          const o2oItemId = values.o2oItemId
          const goodsName = values.goodsName
          const barcode = values.barcode
          const itemCode = values.itemCode
          const shelved = values.shelved
          const status = values.status 
          const page = this.state.current
          const pageSize = this.state.pageSize
          const isSelf = this.isSelf 
          const city = values.city === '全部' ? '' : values.city
        this.changeMsgData(page, pageSize, shopId, channelId,o2oItemId, goodsName, barcode, itemCode, shelved, status, this.state.categoryId, isSelf, city)          
        })
      }
    }else{
      message.error(result.data.err)
      this.setState({
        confirmLoading: false        
        })
    }
  }

  statusChange = (value) => {
    if (value === '禁用'){
      this.setState({
        unableState: true
      })     
    }
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedKeys: selectedRowKeys, selectedRows })
    const unableList = selectedRows.find( data => data.status === '禁用')
    if(unableList !== undefined){
      this.setState({unableStatus: false})
    }else{
      this.setState({unableStatus: true})          
    }
    if(selectedRows.length === 0){
      this.setState({unableStatus: true})
    }
    this.setState({ selectedKeys: selectedRowKeys, selectedRows })
  }

  showLog = (channelId, shopId, itemCode) =>{
    this.setState({
      logChannelId: channelId,
      logShopId : shopId,
      logItemId :itemCode,
      logVisible : true
    })
  }

  showInventory = (channelId, shopId, itemCode) =>{
    this.setState({
      inventoryChannelId: channelId,
      inventoryShopId : shopId,
      inventoryitemCode :itemCode,
      inventoryVisible : true
    })
  }

  handleCancelInventory = (channelId, shopId, itemCode) =>{
    this.setState({
      inventoryChannelId: undefined,
      inventoryShopId : undefined,
      inventoryitemCode :undefined,
      inventoryVisible : false
    })
  }

  handleCancelLog = () =>{
    this.setState({
      logChannelId: undefined,
      logShopId : undefined,
      logItemId :undefined,
      logVisible : false
    })
  }

  treeSelect = ({key , selectedKeys}) =>{
    this.setState({
      categoryId : key,
      treeSelectedKeys: selectedKeys,
    })
    this.refs.storeItemListForm.validateFieldsAndScroll((err , values) => {
      const shopId  = typeof(values.shopId) === 'string' ? [this.props.storeItemStore.shopId] : values.shopId    
      let channelId = values.channelId
      const o2oItemId = values.o2oItemId
      const goodsName = values.goodsName
      const barcode = values.barcode
      const itemCode = values.itemCode
      const shelved = values.shelved
      const status = values.status
      const isSelf = values.isSelf
      const city = values.city === '全部' ? '' : values.city
    this.changeMsgData(this.state.pagination.current,this.state.pagination.pageSize, shopId, channelId, o2oItemId, goodsName, barcode, itemCode, shelved, status,key, isSelf, city)    
    })
  }

  clearCategoryId = () =>{
    this.treeSelect({})
    this.onOpenChange([])
    this.setState({
      changeChannelId: undefined,
      changeShopId: undefined
    })
  }

  clearUnable = () =>{
    this.setState({
      unableStatus: true
    })
    
  }
  onOpenChange = (openkeys) =>{
    this.setState({
      openkeys: openkeys
    })
  }

  onReset  = (page , pageSize) =>{
    this.setState({
      pagination:{
        current: page ,
        pageSize: pageSize
      }
    })
  }

  handleLabelTooltip = (label, limit, total) => {
    if(label.replace(/[^\u0000-\u00ff]/g,"aa").length/2 > limit + 1) {
      let bytesCount = 0, subNum = 0;
      for (let i = 0; i < label.length; i ++) {
        if (/^[\u0000-\u00ff]$/.test(label.charAt(i))) { //匹配双字节
          bytesCount += 1;
        } else {
          bytesCount += 2;
        }
        if(bytesCount > limit*2) {
          break;
        }
        subNum += 1;
      }
      return (<Tooltip placement="right" title={label}>
        {`${label.substring(0,subNum)}...${total !== undefined ? ' (' + total + ')' : ''}`}
      </Tooltip>)
    } else {
      return `${label}${total !== undefined ? ' (' + total + ')' : ''}`;
    }
  }
  
  render() {
    const tagStyle = { width: 54, textAlign: 'center'}
    const columns = [
      {
        title: '个性化',
        dataIndex: 'isSelf',
        key: 'isSelf',
        width: 100,
        render: (text) => (
            <span>
            {text === '否' ? <Tag color="red">{text}</Tag> : null}
            {text === '是' ? <Tag color="green">{text}</Tag> : null}
          </span>
        )
      },
      {
        title: '渠道',
        dataIndex: 'channelName',
        key: 'channelName',
        width: 100,
      },
      {
        title: '家乐福门店',
        dataIndex: 'shopNameAlias',
        key: 'shopNameAlias',
        width: 120,
      }, {
        title: '门店编码',
        dataIndex: 'shopId',
        key: 'shopId', 
        width: 100,        
      }, {
        title: '商品编码',
        dataIndex: 'itemCode',
        key: 'itemCode',
        width: 120,       
      }, {
        title: 'O2O商品编码',
        dataIndex: 'o2oSkuId',
        key: 'o2oSkuId',
        width: 220, 
      }, {
        title: '商品名称',
        dataIndex: 'goodsName',
        key: 'goodsName',
        width: 300, 
      }, {
        title: '英文名称',
        dataIndex: 'goodsEnName',
        key: 'goodsEnName',
        width: 150,
        render: (text, record) => (
            <Tooltip title={record.goodsEnName}>
              <span>{record.goodsEnName!==null ? `${record.goodsEnName.substring(0, 8)}...`: ''}</span>
            </Tooltip>
        )
      },{
        title: '规格销售单位',
        dataIndex: 'specUnit',
        key: 'specUnit',
        width: 150,
        render: (text, record) => <span>{`${record.spec} ${record.unit}`}</span>
      },{
        title: '商品条码',
        dataIndex: 'barCode',
        key: 'barCode',
        width: 200,
      },{
        title: '商品类别',
        dataIndex: 'categoryName',
        key: 'categoryName',
        width: 100,
      }, {
        title: '安全库存',
        dataIndex: 'safeInventory',
        key: 'safeInventory',
        width: 100,
      }, {
        title: '锁定库存',
        dataIndex: 'lockInventory',
        key: 'lockInventory',
        width: 100,
      }, {
        title: 'P4库存',
        dataIndex: 'p4Inventory',
        key: 'p4Inventory',
        width: 100,
      },,{
        title: '可卖数',
        dataIndex: 'actualInventory',
        key: 'actualInventory',
        width: 100,
      },{
        title: '外卖在途销量',
        dataIndex: 'saleQty',
        key: 'saleQty',
        width: 150,
      },{
        title: '售卖价格系数',
        dataIndex: 'priceRate',
        key: 'priceRate',
        width: 150,
      },{
        title: '销售价',
        dataIndex: 'salesPrice',
        key: 'salesPrice',
        width: 100,
      },{
        title: '锁定价',
        dataIndex: 'lockPrice',
        key: 'lockPrice',
        width: 100,
      },{
        title: '成本价',
        dataIndex: 'costPrice',
        key: 'costPrice',
        width: 100,
      },{
        title: '上架状态',
        dataIndex: 'shelved',
        key: 'shelved',
        width: 100, 
      },
      {
        title: '启用状态',
        dataIndex: 'status',
        key: 'status',
        width: 100,
        render: (text, record) => (
          <span>
            {record.status === '未启用' ? <Tag color="orange" style={tagStyle}>{record.status}</Tag> : null}
            {record.status === '启用' ? <Tag color="green" style={tagStyle}>{record.status}</Tag> : null}
            {record.status === '禁用'? <Tag color="red" style={tagStyle}>{record.status}</Tag> : null}
          </span>
          /*<Tooltip title={record.status}>
            {record.status === '未启用' ? <Icon type="close" style={{color: '#f04134'}}/> : null}
            {record.status === '启用' ? <Icon type="check" style={{color: '#00a854'}}/> : null}
            {record.status === '禁用'? <Icon type="minus-circle" style={{color: '#f04134'}}/> : null}
          </Tooltip>*/
      )
      },{
        title: '最近价格同步时间',
        dataIndex: 'priceModifyTime',
        key: 'priceModifyTime',
        width: 200,
      },{
        title: '库存改变最后时间',
        dataIndex: 'inventoryModifyTime',
        key: 'inventoryModifyTime',
        width: 200,
      },{
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        fixed: 'right',
        width: 200,
        render: (text, record) => {
          let channelId = 0        
          switch(record.channelName){
            case '百度外卖' :
              channelId = 10
              break;
            case '饿了么' :
              channelId = 11
              break;
            case '美团' :
              channelId = 12
              break;
            default : 
              channelId = 0
          }
          let status = null
          switch (record.status) {
            case '禁用':
              status = -1
              break
            case '未启用':
              status = 0
              break
            case '启用':
              status = 1
              break
            default:
              status = null
          }
          return (
            <span>
              <a onClick={() =>{this.showDetailModal(record.skuId, channelId, record.itemId, record.shopId, status )}}>编辑</a>
              <span className="ant-divider" />
              <a onClick={() =>{this.showLog(channelId, record.shopId , record.itemCode)}}>操作日志</a> 
              <span className="ant-divider" />
              <a onClick={() =>{this.showInventory(channelId, record.shopId , record.itemCode)}}>库存日志</a>              
            </span>
          )
        }
      }
    ]
    const rowSelection = {
      selectedRowKeys:this.state.selectedKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User',    // Column configuration not to be checked
      }),
    }
    const radioStyle = {
      display: 'block',
      height: '30px',
      lineHeight: '30px',
    }
    let title
    if (this.props.store.collapse) {
      title = <h2 style={{ marginBottom: 16 ,color: '#108ee9'}}>门店商品管理</h2>
    } else {
      title = ''
    }

    return (    
      <div>
        {title}
        <StoreItemListForm 
          ref = 'storeItemListForm'
          onReset = {this.onReset}
          changeMsgData={this.changeMsgData}
          pagination={this.state.pagination}
          shopId = {this.state.changeShopId}
          channelId= {this.state.changeChannelId}
          history = {this.props.history}
          changeFormList = {this.changeFormList}
          categoryId = { this.state.categoryId}
          clearCategoryId ={this.clearCategoryId}
          clearUnable = {this.clearUnable}
          setStatus = {this.setStatus}
          setShelved = {this.setShelved}
          setLockPrice = {this.setLockPrice}
          setLockInventory = {this.setLockInventory}
          setRefresh = {this.setRefresh}
          unableStatus = {this.state.unableStatus}
          initCategoryList = {this.initCategoryList}
          changeCategoryList = {this.changeCategoryList}
        />
        <div>
          <Spin spinning = {this.props.storeItemStore.loading}>
          <div style ={{display : 'flex'}}>
            <div style ={{flex: '0 0 auto', width : 180, maxHeight: this.state.widowHeight-331, overflowY: 'scroll'}}>
            <Menu mode = 'inline' onSelect = {this.treeSelect}  selectedKeys = {this.state.treeSelectedKeys} openKeys ={this.state.openkeys} onOpenChange ={this.onOpenChange} >
              {this.props.storeItemStore.handleCategoryData(this.state.categoryList).map(item=>
                    <Menu.SubMenu key={item.value}
                    title={`${this.handleLabelTooltip(item.label, 7)}`}>
                    {item.children.map(_item =>
                      <Menu.Item key={_item.value}>
                        {this.handleLabelTooltip(_item.label, 5, _item.total)}
                      </Menu.Item>)}
                </Menu.SubMenu>
              )}
            </Menu>
            </div>
            <div className="tableRapper">
            <Table 
            style = {{width : '100%'}}
            rowSelection={rowSelection} 
            columns = {columns} 
            scroll = {{x: 3500,y: this.state.widowHeight-381}}
            dataSource = {this.state.dataSource}
            pagination = {this.state.pagination}
            onChange = {this.handleChange} 
          />
            </div>
          </div>
          </Spin>
          </div>
        <Modal
          visible = {this.state.statusModal}
          title = '设置启用状态'
          onCancel = { () => {this.setState({statusModal: false , loading : false})}}
          onOk = {this.handleStatus}
          confirmLoading={this.state.confirmLoading}
          maskClosable = {false}
        >     
          <RadioGroup onChange={this.onChangeStatus} value={this.state.statusValue}>
            <Radio style={radioStyle} value={1}>启用</Radio>
            <Radio style={radioStyle} value={-1}>禁用</Radio> 
          </RadioGroup>  
        </Modal>
        <Modal
          visible = {this.state.shelvedModal}
          title = '设置上架状态'
          onCancel = { () => {this.setState({shelvedModal: false,  loading : false})}}
          onOk = {this.handleShelved}
          confirmLoading={this.state.confirmLoading}
          maskClosable = {false}
        >
          <RadioGroup onChange={this.onChangeShelved} value={this.state.shelvedValue}>
            <Radio style={radioStyle} value={1}>上架</Radio>
            <Radio style={radioStyle} value={0}>下架</Radio> 
          </RadioGroup>
        </Modal>
        <Modal
          visible = {this.state.lockPriceModal}
          title = '锁定价格'
          onCancel = { () => {this.setState({lockPriceModal: false , loading : false})}}
          onOk = {this.handleLockPrice}
          confirmLoading={this.state.confirmLoading}
          maskClosable = {false}
        >
          <InputNumber  placeholder = '请输入锁定价格' style={{width:'100%'}} size = 'default' value ={this.state.lockPriceValue} onChange ={this.onChangelockPrice}/>
        </Modal>              
        <Modal
          visible = {this.state.lockInventoryModal}
          title = '锁定库存'
          onCancel = { () => {this.setState({lockInventoryModal: false,  loading : false})}}
          onOk = {this.handleLockInventory}
          confirmLoading={this.state.confirmLoading}
          maskClosable = {false}
        >
          <InputNumber  placeholder = '请输入锁定库存' style={{width:'100%'}} size = 'default' value ={this.state.lockInventoryValue} onChange ={this.onChangelockInventory}/>        
        </Modal>                        
        <Modal
          visible = {this.state.detailModal}
          title = '修改商品信息'
          onOk = {this.handleOk}
          onCancel = {this.handleCancel}
          width ={800}
          maskClosable = {false}
        >
          <StoreItemDetail 
            ref = 'StoreItemDetail'
            formSource = {this.state.formSource}
            formLoading= {this.state.formLoading}
            status = { this.state.status}
            unableState = { this.state.unableState}
            statusChange = {this.statusChange}
            categoryList = {this.state.categoryList}
            changePersonnal = {this.changePersonnal}
            changeChecked = {this.changeChecked}
            personnalStatus = {this.state.personnalStatus}
            checkStatus = {this.state.checkStatus}
          />
        </Modal>        
        <Modal
          visible = {this.state.logVisible}
          title = '查看日志'
          onCancel={() => {this.handleCancelLog() }}
          footer={null}
          width ={1000}
          maskClosable = {false}
        >
        <ShopItemLogTable 
          channelId = {this.state.logChannelId}
          shopId = {this.state.logShopId}
          itemId = {this.state.logItemId}
        />
        </Modal>
        <Modal
          visible = {this.state.inventoryVisible}
          title = '查看库存'
          onCancel={() => {this.handleCancelInventory() }}
          footer={null}
          width ={1000}
          maskClosable = {false}
        >
        <InventoryLogTable
          channelId = {this.state.inventoryChannelId}
          shopId = {this.state.inventoryShopId}
          itemCode = {this.state.inventoryitemCode}
        />
        </Modal>
      </div>
    )
  }
}

export default StoreItemComponent

